using System;
using System.Windows.Forms;
using System.Collections.Generic;
using System.Data.Common;
using System.ComponentModel;
using System.Data.Odbc;

namespace Tilver.DBConnectionUI.Editors
{
    [ToolboxItem(false)]
    internal partial class OdbcEditor : UserControl, IUDLEditor
	{
        private OdbcConnectionStringBuilder builder =new OdbcConnectionStringBuilder();
        bool datasourcesPopulated = false;

		public OdbcEditor()
		{
			InitializeComponent();
            this.txDatasource.Validated += delegate { this.SetValue("Dsn", this.txDatasource.Text); };
            this.txDatasource.DropDown += delegate { this.loadDatasources(); };
            this.txUserID.Validated += delegate { this.SetValue("UID", this.txUserID.Text); };
            this.txPassword.Validated += delegate { this.SetValue("Password", this.txPassword.Text); };
            this.ckUseDSN.CheckedChanged += delegate { this.setDataSourceMode(); };
            this.cmdBuildString.Click += delegate { this.buildConnectionString(); };
        
        }

        #region IConnectionEditor Members

        public string ConnectionString
        {
            get
            {
                return builder.ConnectionString;
            }
            set
            {
                try
                {
                    builder.ConnectionString = value;
                    if (builder.Dsn != null && builder.Dsn.Length > 0)
                        this.ckUseDSN.Checked = true;
                    else
                        this.ckUseConnString.Checked = true;
                }
                catch (Exception) { }
                this.RefreshData();
            }
        }

        public void RefreshData()
        {
            if (this.ckUseDSN.Checked)
                this.txDatasource.Text = builder.Dsn;
            else
            {
                this.txConnectionString.Text = builder.ConnectionString;
            }

            this.txUserID.Text = Convert.ToString(GetValue("UID"));
            this.txPassword.Text = Convert.ToString(GetValue("Password"));
        }

        public object GetAdvancedPropertiesObject()
        {
            return builder;
        }

        #endregion

        #region Helper Methods

        void SetValue(string key, object value)
        {
            if (builder.ContainsKey(key))
                builder[key] = value;
        }

        object GetValue(string key)
        {
            if (builder.ContainsKey(key))
                return builder[key];
            return null;
        }

        void setDataSourceMode()
        {
            bool isDsn = this.ckUseDSN.Checked;

            if (isDsn)
            {
                builder = new OdbcConnectionStringBuilder();
            }

            this.txDatasource.Enabled = isDsn;
            this.txConnectionString.Enabled = !isDsn;
            cmdBuildString.Enabled = !isDsn;

            if (isDsn)
                this.txConnectionString.Text = "";
        }

        void loadDatasources()
        {
            if (!datasourcesPopulated)
            {
                string[] dataSources = this.getDataSources();
                this.txDatasource.Items.AddRange(dataSources);

                datasourcesPopulated = true;
            }
        }

        void buildConnectionString()
        {
            string str = OdbcManager.GetODBCConnectionString(this.ParentForm).Trim();

            if (str.Length > 0)
            {
                this.txConnectionString.Text = str;
                builder.ConnectionString = str;
                this.RefreshData();
            }
        }

        string[] getDataSources()
        {
            Guid CLSID_MSDASQL_ENUMERATOR =
                new Guid("C8B522CD-5CF3-11ce-ADE5-00AA0044773D");

            List<string> list = new List<string>();

            System.Data.OleDb.OleDbDataReader enumerator =
                System.Data.OleDb.OleDbEnumerator.GetEnumerator(
                Type.GetTypeFromCLSID(CLSID_MSDASQL_ENUMERATOR));

            using (System.Data.OleDb.OleDbDataReader reader = enumerator)
            {
                while (reader.Read())
                {
                    list.Add(reader["SOURCES_NAME"].ToString());
                }
            }

            return list.ToArray();
        }

        #endregion

    }
}
